<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import { getTodayActiveUserCount } from '@/api/dashboard'

const animationDuration = 6000

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    }
  },
  data() {
    return {
      chart: null,
      timeout: null,
      chartData: {}
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  destroyed() {
    if (this.timeout) {
      clearInterval(this.timeout)
      this.timeout = null
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.loadData()
      this.timeout = setInterval(() => {
        this.loadData()
      }, 1000 * 60)
    },
    loadData() {
      getTodayActiveUserCount().then(({ success, message, data }) => {
        if (success) {
          const xAxis = []
          const yAxis = []
          data = data || []
          for (let i = 0; i <= new Date().getHours(); ++i) {
            xAxis[i] = i + '点'
            const d = data.filter(item => parseInt(item.hour) === i)
            if (d && d.length > 0) {
              yAxis[i] = d[0].count
            } else {
              yAxis[i] = 0
            }
          }
          this.chartData = { xAxis, yAxis }
        }
      })
    },
    setOptions({ xAxis, yAxis } = {}) {
      this.chart.setOption({
        title: {
          text: '当天活跃用户',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          },
          textStyle: {
            color: '#fff'
          }
        },
        grid: {
          top: 30,
          left: '2%',
          right: '2%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [{
          type: 'category',
          data: xAxis,
          axisTick: {
            alignWithLabel: true
          }
        }],
        yAxis: [{
          type: 'value',
          axisTick: {
            show: false
          }
        }],
        series: [{
          name: '用户活跃度',
          type: 'bar',
          stack: 'vistors',
          barWidth: '60%',
          data: yAxis,
          animationDuration
        }]
      })
    }
  }
}
</script>
